package com.asia.order.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtils {
	public static Logger log = LoggerFactory.getLogger(HttpClientUtils.class);
    private static String DEFAULT_CHARSET = "UTF-8";
    private static String DEFAULT_CONTENT_TYPE = "application/json";
    private static int DEFAULT_TIMEOUT = 90000;

    private static String charset(String charset) {
        return charset != null ? charset : DEFAULT_CHARSET;
    }
    private static String contentType(String contentType) {
        return contentType != null ? contentType : DEFAULT_CONTENT_TYPE;
    }

    private static int timeout(Integer timeout) {
        return timeout != null ? timeout : DEFAULT_TIMEOUT;
    }
    
    public static String doPost(String urlString, String param,Map<String,String> headerMap) {
		// 创建返回对象
		StringBuilder result = new StringBuilder();

		URL url = null;
		try {
			url = new URL(urlString);
			URLConnection connection = url.openConnection();
			HttpURLConnection httpconn = (HttpURLConnection) connection;

			// 设置允许输入输出 请求类型
			httpconn.setDoOutput(true);
			httpconn.setDoInput(true);
			httpconn.setUseCaches(false);
			httpconn.setRequestMethod("POST");
			//httpconn.setConnectTimeout(2000);// 设置连接超时时间，单位毫秒  
			//httpconn.setReadTimeout(2000);// 设置读取数据超时时间，单位毫秒  

			// 设置请求头
			
			httpconn.setRequestProperty("accept","*/*");
			httpconn.setRequestProperty("connection", "Keep-Alive");
			httpconn.setRequestProperty("Charset", "UTF-8");
			httpconn.setRequestProperty("Accept-Charset", "UTF-8");
			httpconn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
			//connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

			if(headerMap != null){
				for(Iterator<String> iter = headerMap.keySet().iterator();iter.hasNext();){
					String key = iter.next();
					String value = headerMap.get(key);

					httpconn.setRequestProperty(key,value);
				}
			}

			// 打开连接
			httpconn.connect();
			

			// 获取输出流 传递参数
			OutputStreamWriter out = new OutputStreamWriter(httpconn.getOutputStream(), "UTF-8");
			out.write(param);
			out.flush();
			out.close();

			// 获取输入流 获取返回的数据
			InputStream in = httpconn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			String line;
			while ((line = reader.readLine()) != null) {
				result.append(line);
			}
			
			//System.out.println(httpconn.getResponseMessage());
			reader.close();
			in.close();

			// 关闭连接
			httpconn.disconnect();

		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			
		}

		return result.toString();
	}
    
    public static String doGet(String urlString, Map<String,String> headerMap) {
		// 创建返回对象
		StringBuilder result = new StringBuilder();

		URL url = null;
		try {
			url = new URL(urlString);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			// 设置允许输入输出 请求类型
			conn.setDoInput(true);
			conn.setRequestMethod("GET");

			// 设置请求头
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type", "application/json");

			if(headerMap != null){
				for(Iterator<String> iter = headerMap.keySet().iterator();iter.hasNext();){
					String key = iter.next();
					String value = headerMap.get(key);

					conn.setRequestProperty(key,value);
				}
			}

			// 打开连接
			conn.connect();

			// 获取输入流 获取返回的数据
			InputStream in = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
			String line;
			while ((line = reader.readLine()) != null) {
				result.append(line);
			}
			reader.close();
			in.close();

			// 关闭连接
			conn.disconnect();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return result.toString();
	}

    /**
     * @param url     地址
     * @param params  参数
     * @param timeout 超时时间（可选），如果为空默认 30s
     * @param charset 编码方式（可选），默认UTF-8
     * @return
     * @throws IOException
     */
    public static String post(String url, String params, Integer timeout, String charset, String contentType) throws IOException {
        String result = null;
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout(timeout));
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout(timeout));
        httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset(charset));

        PostMethod postMethod = new PostMethod(url);
        StringRequestEntity requestEntity = new StringRequestEntity(params, contentType(contentType),charset(charset));
        postMethod.setRequestEntity(requestEntity);
        int statusCode = httpClient.executeMethod(postMethod); //状态，一般200为OK状态，其他情况会抛出如404,500,403等错误
        if (statusCode != HttpStatus.SC_OK) {
            try{
                InputStream inputStream = postMethod.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charset(charset)));
                StringBuffer stringBuffer = new StringBuffer();
                String str;
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
                br.close();
                result = stringBuffer.toString();
            }catch (Exception e) {

            }
            throw new IOException("\n访问: " +url+ " 失败。\n 参数：" + params + " \n 返回状态：" + statusCode + "\n 返加数据:" + result);
        } else {
            InputStream inputStream = postMethod.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charset(charset)));
            StringBuffer stringBuffer = new StringBuffer();
            String str;
            while ((str = br.readLine()) != null) {
                stringBuffer.append(str);
            }
            br.close();
            result = stringBuffer.toString();
        }
        httpClient.getHttpConnectionManager().closeIdleConnections(1);
        return result;
    }

    /**
     * @param url     地址
     * @param timeout 超时时间（可选），如果为空默认 30s
     * @param charset 编码方式（可选），默认UTF-8
     * @return
     * @throws IOException
     */
    public static String get(String url, Integer timeout, String charset) throws IOException {
        String result = null;
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout(timeout));
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout(timeout));
        httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset(charset));

        GetMethod getMethod = new GetMethod(url);
        int statusCode = httpClient.executeMethod(getMethod); //状态，一般200为OK状态，其他情况会抛出如404,500,403等错误
        if (statusCode != HttpStatus.SC_OK) {
            try{
                InputStream inputStream = getMethod.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charset(charset)));
                StringBuffer stringBuffer = new StringBuffer();
                String str;
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
                br.close();
                result = stringBuffer.toString();
            }catch (Exception e) {

            }
            throw new IOException("访问: " +url+ " 失败。 \n 返回状态：" + statusCode + "\n 返加数据:" + result);
        } else {
            InputStream inputStream = getMethod.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charset(charset)));
            StringBuffer stringBuffer = new StringBuffer();
            String str;
            while ((str = br.readLine()) != null) {
                stringBuffer.append(str);
            }
            br.close();
            result = stringBuffer.toString();
        }
        httpClient.getHttpConnectionManager().closeIdleConnections(1);
        return result;
    }
    
    public static String getGetResponse(String url, int timeout) {
		String html = "";
		// 构造HttpClient的实例
		HttpClient httpClient = new HttpClient();
		//设置 Http 连接超时
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
		// 创建GET方法的实例
		GetMethod getMethod = new GetMethod(url);
		getMethod.setRequestHeader("Connection", "close");
		try {
			// 执行getMethod
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
			}
			// 处理内容
			html = getMethod.getResponseBodyAsString();
		} catch (HttpException e) {
			// 发生致命的异常，可能是协议不对或者返回的内容有问题
			e.printStackTrace();
		} catch (IOException e) {
			// 发生网络异常
			e.printStackTrace();
		} finally {
			// 释放连接
			getMethod.releaseConnection();
		}
		return html;
	}

	
	public static String postRequestResponse(String url, String request, int timeout) throws Exception {
		String response = "";
		// 构造HttpClient的实例
		HttpClient httpClient = new HttpClient();
		//设置 Http 连接超时
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
		// 创建POST方法的实例
		PostMethod postMethod = new UTF8PostMethod(url); 
//		postMethod.setRequestHeader("Authorization", headerValue);
		postMethod.setRequestHeader("SOAPAction", "");
		try {
			postMethod.setRequestEntity(new StringRequestEntity(request, "text/xml; charset=UTF-8", "UTF-8"));
			// 执行getMethod
			int statusCode = httpClient.executeMethod(postMethod);
			if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED ) {
			}
			// 处理内容
			postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8"); 
			response = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			// 发生致命的异常，可能是协议不对或者返回的内容有问题
			throw e;
        } finally {
			// 释放连接
			postMethod.releaseConnection();
		}
		return response;
	}
	
	/**
	 *	执行getMethod
	 * 	response说明:
	 * 	{
	 * 		"status": 200,  ----返回状态码 200代表成功
	 * 		"result": {
	 * 			"data": [{},{}],
	 * 			"total": 2
	 * 		}
	 * 	}
	 * @param url
	 * @param headerValue
	 * @param timeout
	 * @return
	 * @throws Exception 
	 */
	public static String getRequestResponse(String url, String headerValue, int timeout) throws Exception {
		String response = "";
		// 构造HttpClient的实例
		HttpClient httpClient = new HttpClient();
		//设置 Http 连接超时
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
		// 创建GET方法的实例
		GetMethod getMethod = new UTF8GetMethod(url);
		getMethod.setRequestHeader("Authorization", headerValue);
		try {
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
			}
			// 处理内容
			getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8"); 
			response = getMethod.getResponseBodyAsString();
		} catch (Exception e) {
			// 发生致命的异常，可能是协议不对或者返回的内容有问题
			throw e;
        } finally {
			// 释放连接
			getMethod.releaseConnection();
		}
		return response;
	}
	
	 public static String sendRequestPost(String requestSoap, String serviceAddress, String charSet, String contentType) throws Exception{
	        String resultSoap = "";
	        PostMethod postMethod = new PostMethod(serviceAddress);
	        byte[] b = new byte[0];
	        try {
	            b = requestSoap.getBytes(charSet);
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	        }
	        InputStream is = new ByteArrayInputStream(b, 0, b.length);
	        RequestEntity re = new InputStreamRequestEntity(is, b.length, contentType);
	        postMethod.setRequestEntity(re);

	        HttpClient httpClient = new HttpClient();
	        int statusCode = 0;
	        try {
	            statusCode = httpClient.executeMethod(postMethod);
	        } catch (Exception e) {
	            throw new Exception("调用接口异常", e);
	        }
	        if (statusCode == 200) {
	            try {
	                resultSoap = postMethod.getResponseBodyAsString();
	            } catch (Exception e) {
	                throw new Exception("调用接口异常", e);
	            }
	        } else {
	            throw new Exception("调用接口异常" + statusCode);
	        }

	        return resultSoap;
	    }
	
	public static class UTF8DeleteMethod extends DeleteMethod {
		public UTF8DeleteMethod(String url) {
			super(url);
		}

		public String getRequestCharSet() {
			return super.getRequestCharSet();
		}
	}
	
	public static class UTF8PutMethod extends PutMethod {
		public UTF8PutMethod(String url) {
			super(url);
		}

		public String getRequestCharSet() {
			return super.getRequestCharSet();
		}
	}
	
	public static class UTF8PostMethod extends PostMethod {
		public UTF8PostMethod(String url) {
			super(url);
		}

		public String getRequestCharSet() {
			return super.getRequestCharSet();
		}
	}
	
	public static class UTF8GetMethod extends GetMethod {
		public UTF8GetMethod(String url) {
			super(url);
		}

		public String getRequestCharSet() {
			return super.getRequestCharSet();
		}
	}
	
	/**
	 * 生成TransactionID
	 * 
	 * @return
	 */
	public static String getTransactionID() {
		int cId = 0;
		// 两个随机数相乘，产生一个随机数，再生成一个整数
		cId = (int) (Math.random() * Math.random() * 10000);

		StringBuilder IndentiBillNo = new StringBuilder(DateFormatUtils.format(
				new Date(), "yyyyMMddHHmmss"));
		StringBuilder strId = new StringBuilder(cId + "");
		int lenth = strId.length(); // 获取生成的序列的长度
		if (lenth < 6) {

			for (int i = 0; i < 10 - lenth; i++) {
				IndentiBillNo = IndentiBillNo.append("0");
			}
			IndentiBillNo = IndentiBillNo.append(strId);
		} else {
			IndentiBillNo = IndentiBillNo.append(strId.substring(lenth - 6));
		}
		return "1016" + IndentiBillNo.toString();
	}
	
	/**
	 * 生成TransactionID
	 * @param prefix 前缀
	 * @param len 随机数长度
	 * @param formatDate 要生成的日期格式，可为null，默认为yyyyMMddHHmmsss
	 * @return
	 */
	public static String getTransactionID(String prefix, int len, String formatDate) {
		int cId = 0;
		// 两个随机数相乘，产生一个随机数，再生成一个整数
		cId = (int) (Math.random() * Math.random() * 10000);

		if(StringUtils.isBlank(formatDate)){
			formatDate = "yyyyMMddHHmmsss";
		}
		StringBuilder IndentiBillNo = new StringBuilder(DateFormatUtils.format(
				new Date(), formatDate));
		StringBuilder strId = new StringBuilder(cId + "");
		// 获取生成的序列的长度
		int lenth = strId.length(); 
		// 如果len为0，则直接返回
		if(len == 0){
			return prefix + IndentiBillNo.toString();
		}
		if (lenth < len) {

			for (int i = 0; i < len - lenth; i++) {
				IndentiBillNo = IndentiBillNo.append("0");
			}
			IndentiBillNo = IndentiBillNo.append(strId);
		} else {
			IndentiBillNo = IndentiBillNo.append(strId.substring(lenth - len));
		}
		return prefix + IndentiBillNo.toString();
	}
	
	
    public static void main(String[] args) throws IOException {

    	
    }
}
